////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.more;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.HttpSuperClassStockBaseActivity;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.adapter.NewsListItemAdapter;
import cc.telecomdigital.tdstock.adapter.NewsViewHolder;

/**
 * @author haibo
 */
public class FinetListItemsActivity extends HttpSuperClassStockBaseActivity
{
	protected static final String	TAG						= FinetListItemsActivity.class.getSimpleName();

	public static String			_title;
	public static String			_catId;
	public static String			_vendorId;

	private static final long		SPECIAL_ID_LOAD_NEXT	= 80000l;
	private static final long		SPECIAL_ID_LOAD_EOF		= 70000l;
	private static final long		SPECIAL_ID_LOAD_NONE	= 60000l;
	private static final long		START_ID				= 90000l;

	private ListView				_listView;
	private Button					_toolBtnReturn;
	private TextView				_category_name;

	private NewsListItemAdapter		_newsAdapter;
	private List<NewsViewHolder>	_newsList;
	private String[]				_newsTitleList;
	private String[]				_newsIdList;
	private String[]				_timestamp;
	
	public static boolean isBackCurrentPage = false;
	
	public static Class<? extends Activity>	_fromActivityClass = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.finet);

		_category_name = (TextView) findViewById(R.id.top_bar_title);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");
				((ITDLApplication) getApplicationContext()).setObject(null);

				Intent intent = new Intent(getApplicationContext(), _fromActivityClass);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(_fromActivityClass, intent);
			}
		});

		_messageHandler = null; // this activity no need it.
		_listView = (ListView) findViewById(R.id.more_finet_list);

		_newsList = new ArrayList<NewsViewHolder>();
	}

	private void updateAdapter()
	{
		if (!_newsList.isEmpty())
		{
			_newsList.remove(_newsList.size() - 1); // remove the last item for
			// it just a flag mark the
			// news list.
		}

		long id = START_ID + _newsList.size();
		for (int index = 0, listSize = _newsTitleList == null ? 0
				: _newsTitleList.length; index < listSize; index++)
		{
			id += index;
			NewsViewHolder viewHolder = new NewsViewHolder();
			viewHolder.id = id;
			viewHolder.newsId = _newsIdList[index];
			viewHolder.text = new TextView(this);
			viewHolder.text.setText(_newsTitleList[index]);
			viewHolder.sign = new ImageView(this);
			_newsList.add(viewHolder);
		}
		
		int theLastItemResouceId = 0;
		if (_newsTitleList == null || _newsTitleList.length < 1
				|| _newsList.size() < 1)
		{
			id = SPECIAL_ID_LOAD_NONE;
			theLastItemResouceId = R.string.provide_no_information;
		}
		else if (_newsTitleList.length == 20)
		{
			id = SPECIAL_ID_LOAD_NEXT;
			theLastItemResouceId = R.string.record_tips_next;
		}
		else if (_newsTitleList.length < 20)
		{
			id = SPECIAL_ID_LOAD_EOF;
			theLastItemResouceId = R.string.record_tips_eof;
		}

		// -----create the last item as the mark of the news---------------
		NewsViewHolder viewHolder = new NewsViewHolder();
		viewHolder.id = id;
		viewHolder.text = new TextView(this);
		viewHolder.text.setText(theLastItemResouceId);
		viewHolder.sign = new ImageView(this);
		_newsList.add(viewHolder);
		// -----create the last item as the mark of the news---------------

		_listView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				if (position != -1)
				{
					if (id == SPECIAL_ID_LOAD_NEXT)
					{
						iIsNextMore = true;
						SendHttpRequest();
					}
					else if (id == SPECIAL_ID_LOAD_EOF || id == SPECIAL_ID_LOAD_NONE)
					{
						// do nothing
					}
					else
					{
						FinetListItemContentActivity._iId = _newsList.get(position).newsId;
						FinetListItemContentActivity._iVendor = _vendorId;
						
						FinetListItemContentActivity._btnCaption = _category_name.getText().toString();

						FinetListItemContentActivity._fromActivityClass = FinetListItemsActivity.class;
						Intent intent = new Intent(FinetListItemsActivity.this, FinetListItemContentActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
						SwitchForwardActivity(FinetListItemContentActivity.class, intent);
					}
				}
			}
		});

		if (_listView.getAdapter() == null)
		{
			_newsAdapter = new NewsListItemAdapter(LayoutInflater.from(this), _newsList);
			_listView.setAdapter(_newsAdapter);
		}
		else
		{
			_newsAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onResume()
	{
		iIsNextMore = false;

		super.onResume();
		
		_category_name.setText(_title);

		if (FinetListActivity.class.getSimpleName().equals(_fromActivityClass.getSimpleName())
				|| DXnewsListActivity.class.getSimpleName().equals(_fromActivityClass.getSimpleName()))
		{
			String[] txtRes = getResources().getStringArray(R.array.toolbuttons_more_list);
			_toolBtnReturn.setText(DXnewsListActivity.class.getSimpleName().equals(_fromActivityClass.getSimpleName()) ? txtRes[1] : txtRes[2]);
			txtRes = null;
		}
		_listView.invalidateViews();		
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		
		_timestamp = null;
		_newsTitleList = null;
		_newsIdList = null;
	}
	
	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return MoreGroup.GetActivityGroupHostControl();
	}

	private boolean	iIsNextMore	= false;

	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		TDStockLog.d(TAG, "GetDataFromHttpServer");
		if(_vendorId == null || _catId == null)
			return null;
		
		if(isBackCurrentPage)
		{
			isBackCurrentPage = false;
			return null;
		}
		
		if (iIsNextMore)
		{
			String[] timeParams = HttpAppInfo.GetDataTimeParams(_timestamp, false);

			return HttpAppInfo.SendDjFNewsListRequest(actContext, _vendorId, _catId, timeParams[0], timeParams[1], this);
		}
		else
		{
			if(_newsList != null && _newsAdapter != null)
			{
				_newsList.clear();
				_newsAdapter.notifyDataSetChanged();
			}
			return HttpAppInfo.SendDjFNewsListRequest(actContext, _vendorId, _catId, this);
		}
	}

	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(final H_UserClient_HttpRequest_Result iResult)
	{
		if (!iResult.MStatus.equals("0"))
		{
			iIsNextMore = false;
			ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
			return;
		}

		Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				updateData(iResult.contentStores);
				updateAdapter();
			}
		};
		_messageHandler.post(runnable);
	}

	private void updateData(List<String[]> _list)
	{
		if (!iIsNextMore)
		{
			iIsNextMore = false;
			if (!_newsList.isEmpty())
			{
				_newsList.clear();
			}
		}

		if (_list == null || _list.isEmpty())
		{
			return;
		}
		
		int length = _list.size();
		_newsTitleList = new String[length];
		_newsIdList = new String[length];
		_timestamp = new String[length];
		int item = 0;
		for (String[] array : _list)
		{
			_newsTitleList[item] = String.format("%s  %s ", array[1].substring(0, 16), array[2]);
			_newsIdList[item] = array[0];
			_timestamp[item] = array[1];
			item++;
		}
	}

}
